package com.zhengtoon.mctoon.conv.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bjtoon.framework.utils.http.HttpUtils;
import com.qitoon.framework.core.exception.BusinessException;
import com.zhengtoon.mctoon.conv.bean.session.OrgSessionInfo;
import com.zhengtoon.mctoon.conv.bean.session.OrgSessionResponse;
import com.zhengtoon.mctoon.conv.constant.OrgSessionConstant;
import com.zhengtoon.mctoon.conv.exception.ConvPhotoExceptionCode;

import okhttp3.Headers;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 平台会话工具类
 *
 * @author 144637
 */
public class PlatformSessionUtils {
    public static final Logger log = LoggerFactory.getLogger(PlatformSessionUtils.class);

    private static final String appId = SysConfig.getPropertyValue("plateform.app.id");
//    private static final String appId = "322";

    private static final String tokenValidUrl = SysConfig.getPropertyValue("plateform.userToken.validate.url");
//    private static final String tokenValidUrl = "http://t200.admin.qitoon.com/auth/validateToken";

    /**
     * 企通/政通平台会话校验,获取用户信息
     *
     * @param userToken 平台为应用挂接的userToken令牌
     * @return
     * @author 144637
     */
    public static OrgSessionInfo validateToken(String userToken) {

        Map<String, String> headerMap = new HashedMap();
        headerMap.put("userToken", userToken);
        Headers headers = Headers.of(headerMap);

        Map<String, String> body = new HashedMap();
        body.put("appId", appId);

        String response = HttpUtils.syncFormPostString(tokenValidUrl, headers, body);
        log.info("平台validateToken返回结果==>{}", response);
        OrgSessionResponse orgSessionResponse = JSON.parseObject(response,
                new TypeReference<OrgSessionResponse>() {
                });

        String responseCode = orgSessionResponse.getCode();

        if (OrgSessionConstant.VALID_TOKEN_CODE_SUCCESS.equals(responseCode)) {
            OrgSessionInfo orgSessionInfo = orgSessionResponse.getData();
            return orgSessionInfo;
        } else if (OrgSessionConstant.VALID_TOKEN_CODE_TOKEN_EXPIRED.equals(responseCode)) {
            throw new BusinessException(ConvPhotoExceptionCode.VALID_TOKEN_EXPIRED);
        } else {
            throw new BusinessException(ConvPhotoExceptionCode.VALID_TOKEN_OTHER);
        }
    }

    public static void main(String[] args) {
        OrgSessionInfo orgSessionInfo = validateToken("2787e09a-f5e4-4d8e-9dcd-5e1b3b66d5fa");
        System.out.println(orgSessionInfo);
    }
}
